<?php
/**
 * Here is your custom functions.
 */

function get_task_status(int $status): string
{
    return \app\common\TaskStatus::from($status)->getStatus();
}

function get_login_type(int $type): string
{
    if (empty($type)) return '-';
    return \app\common\LoginType::from($type)->getStatus();
}

function checkMobile(string $mobile = ''): bool|int
{
    return preg_match("/^1[3456789]\d{9}$/", $mobile);
}

/**
 * @param string $par1
 * @param string $par2
 * @return string
 */
function myDate(string $par1 = '', string $par2 = ''): string
{
    if (!empty($par1)) {
        if (is_numeric($par1)) {
            $time = $par1;
        } else {
            $str = $par1;
        }
    }
    if (!empty($par2)) {
        if (is_numeric($par2)) {
            $time = $par2;
        } else {
            $str = $par2;
        }
    }
    if (empty($str)) {
        $str = 'Y-m-d H:i:s';
    }
    if (empty($time)) {
        $time = time();
    }
    return date($str, $time);
}

/**
 * @param $num
 * @return string
 */
function change_byte($num): string
{
    if ($num < 1) return '0 bytes';
    $array = ["B", "KB", "MB", "GB", "TB", "PB"];
    $pos   = 0;
    while ($num >= 1024) {
        $num /= 1024;
        $pos++;
    }
    return round($num, 2) . " " . ($array[$pos] ?? "");
}

function filterStr(string $str): string
{
    $str = str_replace([" ", "　", "\n", "\r", "\t"], '', $str);
    $str = urlencode($str);
    $str = preg_replace("/(%E3%80%82|%EF%BC%9F|%EF%BC%81|%EF%BC%8C|%E3%80%81|%EF%BC%9B|%EF%BC%9A|%E2%80%9C|%E2%80%9D|%E2%80%98|%E2%80%99|%EF%BC%88|%EF%BC%89|%E3%80%8A|%E3%80%8B|%E3%80%88|%E3%80%89|%E3%80%90|%E3%80%91|%E3%80%8E|%E3%80%8F|%E3%80%8C|%E3%80%8D|%EF%B9%83|%EF%B9%84|%E3%80%94|%E3%80%95|%E2%80%A6|%E2%80%94|%EF%BD%9E|%EF%B9%8F|%EF%BF%A5|%2C|%2F|%3C|%3E|%3F|%3B|%3A|%22|%27|%7C|%5B|%5D|%7B|%7D|%60|%7E|%21|%23|%40|%24|%25|%5E|%26|%2A|%28|%29|%5C)+/", '', $str);
    return urldecode($str);
}

function get_user_last_login_type(int $uid = 0): string
{
    $login_type = \app\model\UserLoginLog::getField(['uid' => $uid], 'login_type', 3600 * 2);
    return get_login_type($login_type);
}

function randomDate($begin_time, $end_time = "", $is = true, $type = 'date'): int|string
{
    $begin     = strtotime($begin_time);
    $end       = $end_time == "" ? mktime() : strtotime($end_time);
    $timestamp = rand($begin, $end);
    return $is ? ($type == 'date' ? date("Y-m-d", $timestamp) : date("Y-m-d h:i:s", $timestamp)) : $timestamp;
}

/**
 * @param $tel
 * @return bool
 */
function is_mobile($tel): bool
{
    if (preg_match('/^(1(3|4|5|6|7|8|9)[0-9])\d{8}$/', $tel)) {
        return true;
    } else {
        return false;
    }
}

function diff_between_day($day1, $day2): float|int
{
    $second1 = strtotime($day1);
    $second2 = strtotime($day2);
    if ($second1 < $second2) {
        $tmp     = $second2;
        $second2 = $second1;
        $second1 = $tmp;
    }
    return round(($second1 - $second2) / 86400);
}

function password_admin($value): string
{
    $value = sha1('blog_') . md5($value) . md5('_encrypt') . sha1($value);
    return sha1($value);
}

function type_to_object(array $array): array
{
    $args = [];
    foreach ($array as $key => $item) {
        $args[] = ['type' => $key, 'title' => $item,];
    }
    return $args;
}

function array_value_sum(...$array): array
{
    $res = [];
    foreach (func_get_args() as $arr) {
        foreach ($arr as $k => $v) {
            if (!isset($res[$k])) {
                $res[$k] = $v;
            } else {
                $res[$k] += $v;
            }
        }
    }
    return $res;
}

/**
 * 秒数转换成时分秒
 *
 * @param int $seconds 122522s
 * @return string 34：02：02
 */
function changeTimeType(int $seconds): string
{
    if (!$seconds) return 0;

    if ($seconds > 3600) {
        $hours = intval($seconds / 3600);
        if ($hours < 10) $hours = '0' . $hours;

        $minutes = $seconds % 3600;
        $minutes = intval($minutes / 60);
        if ($minutes < 10) $minutes = '0' . $minutes;

        $seconds = $seconds % 60;
        if ($seconds < 10) $seconds = '0' . $seconds;

        return $hours . ':' . $minutes . ':' . $seconds;
    }

    $minutes = intval($seconds / 60);
    if ($minutes < 10) $minutes = '0' . $minutes;

    $seconds = $seconds % 60;
    if ($seconds < 10) $seconds = '0' . $seconds;

    return $minutes . ':' . $seconds;
}

//截取某子字符串前的字符串
function getBeforeString($string, $beforeString)
{
    return substr($string, 0, strpos($string, $beforeString));
}

//截取某子字符串后的字符串
function getLaterString($string, $laterString)
{
    return substr($string, (stripos($string, $laterString) + strlen($laterString)));
}

//过滤字符串只保留字母、数字
function getFilterStr($str)
{
    preg_match_all('/[a-zA-Z0-9]/u', $str, $result);
    return implode('', $result[0]);
}

/**
 * 通过CURL发送HTTP请求
 *
 * @param string $url        //请求URL
 * @param array  $postFields //请求参数
 * @return mixed
 *
 */
function curlPost(string $url, $data = null, $header = ['Content-Type: application/json; charset=utf-8'])
{
//    if (is_array($data)) {
//        $data = http_build_query($data);
//    }
    $data = json_encode($data);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_HEADER, false);//不返回头部信息
    curl_setopt($ch, CURLOPT_POST, 1);
    if ($data != null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  //结果是否显示出来，1不显示，0显示
    //判断是否https
    if (strpos($url, 'https://') !== false) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $UserAgent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; .NET CLR 3.5.21022; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
        curl_setopt($ch, CURLOPT_USERAGENT, $UserAgent);
    }
    $data = curl_exec($ch);
    curl_close($ch);

    if ($data === FALSE) {
        $data = ['code' => 400, 'msg' => curl_error($ch)];
    }

    return ['code' => 200, 'data' => json_decode($data, true)];
}

/**
 * 通过CURL发送HTTP请求Get
 *
 * @param string $url //请求URL https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx35b3721
 * @return array
 *
 */
function curlGet($url, $type = 1)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_TIMEOUT, 5000);
    //判断是否https
    if (strpos($url, 'https://') !== false) {
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        $UserAgent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; .NET CLR 3.5.21022; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
        curl_setopt($curl, CURLOPT_USERAGENT, $UserAgent);
    }
    curl_setopt($curl, CURLOPT_URL, $url);
    if ($type == 1) {
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    }
    $res = curl_exec($curl);

    if (!$res) {
        $error = curl_errno($curl);
        curl_close($curl);
        return ['code' => 400, 'msg' => $error];
    }

    curl_close($curl);
    return ['code' => 200, 'data' => json_decode($res, true)];
}

/**
 * 时间戳转化为日期
 *
 * @param int    $time   时间戳
 * @param string $format 日期格式化方式
 * @return string 日期
 */
function millisecondTimeToformat(int $time, string $format = 'Y-m-d H:i:s'): string
{
    return date($format, substr($time, 0, 10));
}

/**
 * 字节转化
 *
 * @param integer $byte
 *
 * @return string
 * @author OwenZhang
 * @date   2021-11-29 23:46:41
 *
 */
function byte_size(int $byte): string
{
    $p      = 0;
    $format = 'bytes';

    if ($byte > 0 && $byte < 1024) {
        $p = 0;
        return number_format($byte) . ' ' . $format;
    }

    if ($byte >= 1024 && $byte < pow(1024, 2)) {
        $p      = 1;
        $format = 'KB';
    }

    if ($byte >= pow(1024, 2) && $byte < pow(1024, 3)) {
        $p      = 2;
        $format = 'MB';
    }

    if ($byte >= pow(1024, 3) && $byte < pow(1024, 4)) {
        $p      = 3;
        $format = 'GB';
    }

    if ($byte >= pow(1024, 4) && $byte < pow(1024, 5)) {
        $p      = 3;
        $format = 'TB';
    }

    $byte /= pow(1024, $p);

    return number_format($byte, 3) . ' ' . $format;
}


/**
 * 获取随机数
 *
 * @param integer $length
 *
 * @return string
 * @author OwenZhang
 * @date   2021-11-29 23:46:41
 *
 */
function getNonce(int $length = 16): string
{
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $str   = '';
    for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
}

//数组转xml
function arrayToXml($arr)
{
    $xml = "<xml>";
    foreach ($arr as $key => $val) {
        if (is_numeric($val)) {
            $xml .= sprintf("<%s>%s</%s>", $key, $val, $key);
        } else {
            $xml .= sprintf("<%s><![CDATA[%s]]></%s>", $key, $val, $key);
        }
    }
    $xml .= "</xml>";
    return $xml;
}

/*
 * 把数组转化成任何你想要的对象类型的数组：
 */
if (!function_exists('arrayToObject')) {
    function arrayToObject($array)
    {
        $aboutVideoArr = array();
        if (is_array($array)) {
            foreach ($array as $value) {
                $video = new Video();
                foreach ($value as $key => $val) {
                    $video->$key = $val;
                }
                array_push($aboutVideoArr, $video);
            }
        } else {
            $video = $array;
        }
        return $aboutVideoArr;
    }
}

/*
 * 把对象转化成普通的数组：
 */
if (!function_exists('objectToarray')) {
    function objectToarray($object)
    {
        if (is_object($object)) {
            foreach ($object as $key => $value) {
                $array[$key] = $value;
            }
        } else {
            $array = $object;
        }
        return $array;
    }
}

/*
 * 获取ip
 */
if (!function_exists('getIP')) {
    function getIP()
    {
        if (getenv('HTTP_CLIENT_IP')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('HTTP_X_FORWARDED')) {
            $ip = getenv('HTTP_X_FORWARDED');
        } elseif (getenv('HTTP_FORWARDED_FOR')) {
            $ip = getenv('HTTP_FORWARDED_FOR');

        } elseif (getenv('HTTP_FORWARDED')) {
            $ip = getenv('HTTP_FORWARDED');
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return $ip;
    }
}
/*
 * 获取手机带星
 */
if (!function_exists('getMobileStars')) {
    function getMobileStars($mobile)
    {
        return substr($mobile, 0, 3) . '****' . substr($mobile, -4);
    }
}

/**
 * 获取2个时间内的所有日期
 *
 * @access public
 * @param string $startDate 开始时间2019-12-30
 * @param string $backDate  结束时间2020-01-02
 * @return array 返回类型
 *                          array(4) {
 *                          [0]=>
 *                          string(10) "2019-12-30"
 *                          [1]=>
 *                          string(10) "2019-12-31"
 *                          [2]=>
 *                          string(10) "2020-01-01"
 *                          }
 */
if (!function_exists('getBetweenTimeArr')) {
    function getBetweenTimeArr($startDate, $backDate)
    {
        if (!$startDate || !$backDate) {
            return [];
        }

        $dtStart           = strtotime($startDate);
        $dt_end            = strtotime($backDate);
        $getBetweenTimeArr = [];

        while ($dtStart <= $dt_end) {
            $getBetweenTimeArr[] = date('Y-m-d', $dtStart);
            $dtStart             = strtotime('+1 day', $dtStart);
        }

        return $getBetweenTimeArr;
    }
}